﻿using System;
using System.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;
using Microsoft.Extensions.Configuration;

namespace XStudio.Common
{
    public class MySqlDbBase : DbBase
    {
        //连接字符串
        static string _connStr;

        //连接对象
        protected DbConnection Conn => _conn ?? (_conn = GetOpenConn());

        public MySqlDbBase()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Environment.CurrentDirectory)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            var configRoot = builder.Build();
            _connStr = configRoot.GetSection("Db").GetSection("MySql").GetSection("connStr").Value;
        }

        ///连接数据库
        public static MySqlConnection GetOpenConn()
        {
            var connection = new MySqlConnection(_connStr);
            connection.Open();
            return connection;
        }

        //关闭
        public MySqlConnection GetClosedConn()
        {
            var conn = new MySqlConnection(_connStr);
            if (conn.State != ConnectionState.Closed) throw new InvalidOperationException("should be closed!");
            return conn;
        }

    }

}
